package com.demo.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * LoginSuccessHandler
 *
 * @author liujin
 * @date 2020/12/8 22:20
 */
@Slf4j
@Component
public class LoginSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Resource
    private ClientDetailsService clientDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    private final String CLIENT_ID = "client_admin";

    private final String CLIENT_SECRET = "secret_9527";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        log.info("login success ...");

        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(CLIENT_ID);
        if (clientDetails == null) {
            throw new UnapprovedClientAuthenticationException("clientId 不存在:" + CLIENT_ID);
        } else if (!passwordEncoder.matches(CLIENT_SECRET, clientDetails.getClientSecret())) {
            throw new UnapprovedClientAuthenticationException("clientSecret 不匹配:" + CLIENT_ID);
        }
        //密码授权 模式, 组建 authentication
        TokenRequest tokenRequest = new TokenRequest(new HashMap<>(), CLIENT_ID, clientDetails.getScope(), "password");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        String jwtToken = token.getValue();
        String jwtRefreshToken = token.getRefreshToken().getValue();
        String tokenType = token.getTokenType();
        Date expiration = token.getExpiration();

        JSONObject tokenJson = new JSONObject();
        tokenJson.put("jwtToken", jwtToken);
        tokenJson.put("jwtRefreshToken", jwtRefreshToken);
        tokenJson.put("tokenType", tokenType);
        tokenJson.put("expiration", expiration);

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(tokenJson.toJSONString());
    }
}
